Imports RemoteAssistanceHelper2.Config_Data

Public Class Form1

	'//I know I shouldn't have but I re-used the button_click code and called in from Form_Load.
	'//This should be in its own function, but it was late and I was tired. -EP
    Private Sub btnRequestAssistance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRequestAssistance.Click
        Dim strComputerName As String = Net.Dns.GetHostName()
        Dim strUserName As String = My.User.Name
        Dim intTest As Boolean = False
        Dim strTicketLocation As String = String.Empty
        Dim f As New ProgressBarForm
        Dim t As New Threading.Thread(New Threading.ThreadStart(AddressOf f.ShowProgress))
        t.Start()

        '//Function makeRaTicket([in] User_Name, [in] Computer_Name, [out] Ticket_Location) as Boolean
        intTest = makeRaTicket(strUserName, strComputerName, strTicketLocation)
        If intTest Then
            If Not TryCifsCopy(strTicketLocation, S_salemTicketDropPath) Then
                If Not TryAltCopy(strTicketLocation, S_salemTicketAltPath) Then
                    t.Abort()
                    MessageBox.Show("Unable to upload Remote Assistance request ticket.", "Remote Assistance Helper :: Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End If
            End If
        End If
        Threading.Thread.Sleep(5000)
        '//End the running thread for progress bar
        t.Abort()

        '//Cleanup thread components
        t = Nothing
		
		Me.TopMost = True
        MessageBox.Show("Remote Assistance Request has been sent.", "Remote Assistance Helper", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Application.Exit()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim errState As Boolean = False

        Try
            ReadXMLConfig()
        Catch o_Exception As Exception
            MessageBox.Show("Unable to read XML config file." & vbCrLf & "This application will now exit", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            errState = True
            Application.Exit()
        End Try

        Try
            CheckAndSetRegistry()
        Catch ex As Exception
            MessageBox.Show("Unable to set registry parameters to enable unsolicited remote assistance." & vbCrLf & _
            "This application will now exit" & vbCrLf & ex.Message & vbCrLf & ex.StackTrace, _
            "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            errState = True
            Application.Exit()
        End Try


        '//Fire the remote assistance request...
        If Not errState Then
            btnRequestAssistance_Click(New Object, New EventArgs)
        End If
    End Sub

    Function TryCifsCopy(ByVal strSourceFile As String, ByVal strDestDir As String) As Boolean
        Dim strDestFile As String = String.Empty
        If strSourceFile.Contains("\") Then
            Dim fileName() As String = strSourceFile.Split("\")
            '//Get just the file name from the source file path.
            strDestFile = strDestDir & fileName(fileName.GetUpperBound(0))
        Else
            strDestFile = strSourceFile
        End If

        '//Try copying the file to SALEM_PATH
        Try
            '//copy the file
            IO.File.Copy(strSourceFile, strDestFile)
            '//delete the file if copied
            IO.File.Delete(strSourceFile)
        Catch ex As Exception
            Return False
        End Try

        '//If we get here, there were no errors
        Return True
    End Function


    Function TryAltCopy(ByVal strSourceFile As String, ByVal strDestination As String) As Boolean
        Dim anonPassword As String = My.User.Name.Split("\")(1) & "@" & My.Computer.Name
        Dim strDestFile As String = String.Empty
        Dim useFTP As Boolean = False
        Dim useDAV As Boolean = False

        If strSourceFile.Contains("\") Then
            Dim fileName() As String = strSourceFile.Split("\")
            '//Get just the file name from the source file path.
            strDestFile = strDestination & fileName(fileName.GetUpperBound(0))
        Else
            strDestFile = strSourceFile
        End If

        '//Should we use WebDAV or FTP?
        If strDestination.Contains("ftp://") Then
            useFTP = True
            useDAV = False
        ElseIf strDestination.Contains("http://") Then
            useFTP = False
            useDAV = True
        ElseIf strDestination.Contains("https://") Then
            useFTP = False
            useDAV = True
        End If

        If useFTP Then
            Try
                My.Computer.Network.UploadFile(strSourceFile, strDestFile, "anonymous", anonPassword, _
                                               False, 30000, FileIO.UICancelOption.ThrowException)
                IO.File.Delete(strSourceFile)
            Catch ex As Exception
                Return False
            End Try
        ElseIf useDAV Then
            Try
                UploadFile(strDestination, strSourceFile, New Net.NetworkCredential("", ""))
            Catch ex As Exception
                Return False
            End Try
        Else
            Return False
        End If

        '//If we get here, there were no errors
        Return True
    End Function


    Function UploadFile(ByRef baseURI As String, ByRef localFileName As String, ByRef creds As Net.NetworkCredential) As Boolean
        Dim ret As Boolean = False
        Dim srvRes As Byte()

        Dim fNIndexOfSlash As Integer = localFileName.LastIndexOf("\") + 1
        Dim fNLength As Integer = localFileName.Length - fNIndexOfSlash
        Dim filename As String = localFileName.Substring(fNIndexOfSlash, fNLength)

        If Not baseURI.EndsWith("/") Then
            baseURI &= "/"
        End If

        Dim wc As New System.Net.WebClient
        wc.UseDefaultCredentials = False
        wc.Credentials = creds
        'If useDAV = True Then
        srvRes = wc.UploadFile(New Uri(baseURI & filename), "PUT", localFileName)
        'ElseIf useFTP = True Then
        '    srvRes = wc.UploadFile(New Uri(baseURI & filename), localFileName)
        'End If

        wc.Dispose()
        If srvRes.Length = 0 Then
            ret = True
        End If
        Return ret
    End Function

    Sub CheckAndSetRegistry()
        '//This code block checks for and enables Unsolicited Remote Assistance ticktet generation
        '//See: http://support.microsoft.com/kb/301527
        '//and: http://msdn2.microsoft.com/en-us/library/ms811079.aspx

        Dim PermKeyname As String = "Software\policies\Microsoft\Windows NT\Terminal Services"
        Dim DACLkeyname As String = "Software\policies\Microsoft\Windows NT\Terminal Services\RAUnsolicit"
        Dim PermValueName As String = "fAllowUnsolicited"
        Dim PermValueName2 As String = "fAllowUnsolicitedFullControl"

        Dim PermValue As String = String.Empty
        Dim permValue2 As String = String.Empty
        Dim getValueFailed As Boolean = False

        '//Enable unsolicited remote assistance requests
        Dim PermRegKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.LocalMachine.OpenSubKey(PermKeyname, False)
        Try
            PermValue = PermRegKey.GetValue(PermValueName).ToString
            permValue2 = PermRegKey.GetValue(PermValueName2).ToString
            If Not PermValue = "1" Then
                getValueFailed = True
            End If
            If Not permValue2 = "1" Then
                getValueFailed = True
            End If
        Catch ex As Exception
            getValueFailed = True
        End Try

        If getValueFailed Then
            PermRegKey = My.Computer.Registry.LocalMachine.OpenSubKey(PermKeyname, True)
            Try
                PermRegKey.SetValue(PermValueName, 1)
                PermRegKey.SetValue(PermValueName2, 1)
            Catch ex As Exception
                Throw ex
            End Try
        End If

        '//Set permissions for members of the administrators group
        Dim DACLregKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.LocalMachine.OpenSubKey(DACLkeyname, False)
        Try
            PermRegKey.GetValue("Administrators")
        Catch ex As Exception
            Try
                DACLregKey = My.Computer.Registry.LocalMachine.OpenSubKey(DACLkeyname, True)
                PermRegKey.SetValue("Administrators", "Administrators")
            Catch ex2 As Exception
                Throw ex2
            End Try
        End Try
    End Sub

End Class
